package cart

import (
	// "fmt"

	"mall/common/utils/pointy"
	enum "mall/service/backend/common/enum/promotion"
	"mall/service/setting/rpc/settingclient"

	"github.com/shopspring/decimal"
	// "github.com/sirupsen/logrus"
	// "github.com/zeromicro/go-zero/core/logx"
)

// ShipmentInfoHandler 获取运费信息handler
type ShipmentInfoHandler struct {
	// 合成复用Next
	Next
}

// Do 获取运费信息的逻辑
func (h *ShipmentInfoHandler) Do(c *Context) (err error) {
	if !c.Resp.StockValid {
		return
	}

	if c.Resp.Total == nil || *c.Resp.Total == 0 {
		return
	}

	if !c.Resp.AddressValid {
		return
	}

	if c.Resp.Address == nil || c.Resp.Address.RegionCode == nil {
		return
	}

	// logx.Infow("获取运费信息...")

	var list []*settingclient.FreightInfo
	list = append(list, &settingclient.FreightInfo{
		// TemplateId: templateId,
		// SkuId: skuId,
		Number: pointy.GetPointer(uint64(c.SkusNumber)),
		Amount: pointy.GetPointer(c.SkusAmount.Truncate(4).String()),
		Weight: pointy.GetPointer(c.SkusWeight.Truncate(5).String()),
		// Volumn: c.Volumn,
	})
	res, err := c.SvcCtx.SettingRpc.GetFreight(c.Ctx, &settingclient.FreightReq{
		Regions: c.Resp.Address.RegionCode,
		List:    list,
	})
	if err != nil {
		return err
	}

	// logrus.Info(fmt.Sprintf("ShipmentInfoHandler GetFreight: %+v", res))
	if len(res.List) > 0 {
		var freight decimal.Decimal
		for _, v := range res.List {
			if v.Freight != nil && len(*v.Freight) > 0 {
				if val, err := decimal.NewFromString(*v.Freight); err == nil {
					freight = freight.Add(val)
				}
			}
		}
		c.Freight = freight
		c.FinalFreight = freight
	}

	for k, info := range c.Modifiers {
		if info.Status == int(0) { // 尚未生效的修正
			// logrus.Info(fmt.Sprintf("ShipmentInfoHandler Modifiers: %+v", info))
			if info.EffectType == enum.PromotionEffectTypeFreeShipping {
				if info.Effect == enum.PromotionEffectOrderFreeShipping {
					if info.ActivityId > 0 {
						info.ActivityAmount = c.Freight
						c.ActivityAmount = c.ActivityAmount.Add(c.Freight)
					}
					if info.CouponId > 0 {
						info.CouponAmount = c.Freight
						c.CouponAmount = c.CouponAmount.Add(c.Freight)
					}
					info.Status = int(1)
					c.Modifiers[k] = info
					c.FinalFreight = decimal.NewFromInt(int64(0))
					break
				}
			}
		}
	}

	return
}
